/***by chaituan@126.com***/
var maxsize = 1048576;//超过1M进行压缩 字节(b
/**
 * [compress 压缩图片]
 * @param  {[dom]} sourceImg [图片dom]
 * @param  {[int]0-1} scale     [缩小的尺寸比例]
 * @param  {[int]0-100} quality   [清晰质量]
 * @return {[object]}           [图片源]
 */
function compress(sourceImg,scale,quality,file){
	if(file.size <= maxsize)return file;//没有超过指定大小则不进行压缩
	if(sourceImg.width > sourceImg.height){
		if(sourceImg.width >= 1000){//超过规定宽带则自动压缩，传入参数则失效
			scale = (1000/sourceImg.width).toFixed(2);
		}
	}else{
		if(sourceImg.height >= 1280){//超过规定宽带则自动压缩，传入参数则失效
			scale = (1000/sourceImg.height).toFixed(2);
		}
	}
	
    var area = sourceImg.width * sourceImg.height,//源图片的总大小
        height = sourceImg.height * scale,
        width = sourceImg.width * scale,
        compressCvs = document.createElement('canvas');//压缩的图片画布
    //压缩的图片配置宽高
    compressCvs.width = width;
    compressCvs.height = height;
    var compressCtx = compressCvs.getContext("2d");
    //解决ios 图片大于2000000像素无法用drawImage的bug
    if(area > 2000000 && navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
        //瓦片绘制
        var smallCvs = document.createElement("canvas"),
            smallCtx = smallCvs.getContext("2d"),
            count = Math.ceil(area / 1000000),//分割的数量
            cvsWidth = width / count,//每个小canvas的宽度
            picWidth = sourceImg.width / count;//分割成小图片的宽度
        smallCvs.height = compressCvs.height;
        smallCvs.width =  width / count;
        //拼凑成大的canvas
        for(var i = 0;i < count;i ++){
            smallCtx.drawImage(sourceImg,i*picWidth,0,picWidth,sourceImg.height,0,0,cvsWidth,height);
            compressCtx.drawImage(smallCvs,i*cvsWidth,0,cvsWidth,height);
        }
    }else{
        compressCtx.drawImage(sourceImg,0,0,sourceImg.width,sourceImg.height,0,0,width,height);
    }
    //将canvas转换成base64
    return dataURLtoBlob(compressCvs.toDataURL(file.type,quality/100),file.name);
}


/**
 * [dataURLtoBlob 将base64转换为blob对象]
 * @param  {[type]} dataurl [图片源base64]
 * @return {[object]}         [图片源blob对象]
 */
function dataURLtoBlob(dataurl,name) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    var b = new Blob([u8arr], {type:mime});
    b.name = name;
    return b;
}